<template>
  <div class="chart-page">
    <!-- 项目选择 -->
    <div class="filter-container">
      <h2>试验工时统计</h2>
      <div class="selectors">
        <div class="selector-item">
          <span>选择项目: </span>
          <a-select
            v-model="selectedProject"
            :options="projectOptions"
            style="width: 300px"
            placeholder="请选择项目"
            @change="handleProjectChange"
          />
        </div>
        <div class="selector-item" v-if="selectedProject">
          <span>选择时间段: </span>
          <a-range-picker
            v-model="selectedTimeRange"
            style="width: 300px"
            :placeholder="['开始日期', '结束日期']"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleTimeRangeChange"
          />
        </div>
        <a-button 
          @click="fetchWorkloadData" 
          :disabled="!selectedProject || !selectedTimeRange || selectedTimeRange.length !== 2"
          :loading="loading"
          type="primary"
        >
          <template #icon><icon-search /></template>
          查询
        </a-button>
        <a-button @click="handleReset">
          <template #icon><icon-refresh /></template>
          重置
        </a-button>
      </div>
    </div>

    <!-- 新增项目工时统计区域 -->
    <div v-if="selectedTimeRange && selectedTimeRange.length === 2" class="project-stats-section">
      <div class="section-title">所有项目工时概览</div>
      <div class="project-charts">
        <div class="project-chart-box">
          <div ref="projectChartContainer" class="chart-item"></div>
        </div>
        <div class="project-table-box">
          <div class="table-header">所有项目工时明细</div>
          <div class="table-scroll">
            <a-table
              :columns="projectColumns"
              :data="projectTableData"
              :pagination="false"
              :bordered="true"
              :scroll="{ y: 300 }"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 图表展示 -->
    <div v-if="selectedProject && selectedTimeRange && selectedTimeRange.length === 2" class="main-content">
      <!-- 人员统计区域 -->
      <div class="stats-section">
        <div class="section-title">试验人员工时统计</div>
        <div class="stats-content">
          <div class="chart-box">
            <div ref="userChartContainer" class="chart-item"></div>
          </div>
          <div class="table-box">
            <div class="table-header">试验人员工时明细</div>
            <div class="table-scroll">
              <a-table
                :columns="userColumns"
                :data="userTableData"
                :pagination="false"
                :bordered="true"
                :scroll="{ x: 600, y: 300 }"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 试验地点统计区域 -->
      <div class="stats-section">
        <div class="section-title">试验地点工时统计</div>
        <div class="stats-content">
          <div class="chart-box">
            <div ref="locChartContainer" class="chart-item"></div>
          </div>
          <div class="table-box">
            <div class="table-header">试验地点工时明细</div>
            <div class="table-scroll">
              <a-table
                :columns="locColumns"
                :data="locTableData"
                :pagination="false"
                :bordered="true"
                :scroll="{ x: 600, y: 300 }"
              />
            </div>
          </div>
        </div>
      </div>
    </div>


    <!-- 空状态提示 -->
    <div v-if="!selectedTimeRange || selectedTimeRange.length !== 2" class="empty-state">
      <div class="empty-content">
        <icon-file />
        <p>请选择时间段查看统计数据</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import * as echarts from 'echarts'
import { 
  listProjectStats, 
  listUserWorkloadStats,
  listAllProjectWorkloadStats,
  listLocWorkloadStats
} from '@/apis/task/taskSituationChart'
import dayjs from 'dayjs'


const projectChartContainer = ref<HTMLElement>()
const userChartContainer = ref<HTMLElement>()
const locChartContainer = ref<HTMLElement>()
let userChart: echarts.ECharts | null = null
let projectChart: echarts.ECharts | null = null
let locChart: echarts.ECharts | null = null




// 选择器数据
const selectedProject = ref<number | null>(null)
const selectedTimeRange = ref<string[]>([]) // 改为数组格式，存储开始和结束日期
const projectOptions = ref<{value: number, label: string}[]>([])
const loading = ref(false) // 添加加载状态

// 表格数据
const userColumns = [
  {
    title: '试验人员',
    dataIndex: 'userName',
    width: 120,
    fixed: 'left'
  },
  {
    title: '试验时数(h)',
    dataIndex: 'testHour',
    width: 100
  },
  {
    title: '试验准备时数(h)',
    dataIndex: 'prepHour',
    width: 120
  },
  {
    title: '加班时数(h)',
    dataIndex: 'overtimeHour',
    width: 100
  }
]

// 试验地点表格列定义
const locColumns = [
  {
    title: '试验地点',
    dataIndex: 'locName',
    width: 150,
    fixed: 'left'
  },
  {
    title: '试验时数(h)',
    dataIndex: 'testHour',
    width: 100
  },
  {
    title: '试验准备时数(h)',
    dataIndex: 'prepHour',
    width: 120
  },
  {
    title: '天数',
    dataIndex: 'workDays',
    width: 100
  }
]

// 新增表格列定义
// 修改项目表格列定义，增加试验时数
const projectColumns = [
  {
    title: '项目名称',
    dataIndex: 'projectName',
    width: 200,
    fixed: 'left'
  },
  {
    title: '试验时数(h)',
    dataIndex: 'testHour',
    width: 100
  },
  {
    title: '试验准备时数(h)',
    dataIndex: 'prepHour',
    width: 120
  },
  {
    title: '加班时数(h)',
    dataIndex: 'overtimeHour',
    width: 100
  },
  {
    title: '总工时(h)',
    dataIndex: 'totalHour',
    width: 100
  }
]

const projectTableData = ref<any[]>([])
const userTableData = ref<any[]>([])
const deviceTableData = ref<any[]>([])
const locTableData = ref<any[]>([])

// 获取项目列表
const fetchProjects = async () => {
  try {
    const res = await listProjectStats()
    if (res.success && res.data && res.data.data) {
      projectOptions.value = res.data.data.map((item: any) => ({
        value: item.id,
        label: `${item.name} (${item.taskCount}个任务)`
      }))
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
  }
}

// 项目变更时自动查询（保持时间段）
const handleProjectChange = async (projectId: number) => {
  userTableData.value = []
  deviceTableData.value = []
  locTableData.value = []
  disposeCharts()
  
  // 如果已经有选择的时间段，自动触发查询
  if (selectedTimeRange.value && selectedTimeRange.value.length === 2) {
    await fetchWorkloadData()
  }
}

// 时间范围变更处理
const handleTimeRangeChange = (dates: string[]) => {
  if (dates && dates.length === 2) {
    const startDate = dayjs(dates[0])
    const endDate = dayjs(dates[1])
    
    if (endDate.isBefore(startDate)) {
      console.error('结束日期不能早于开始日期')
      return
    }
  }
}

// 重置查询条件
const handleReset = () => {
  selectedProject.value = null
  selectedTimeRange.value = []
  projectTableData.value = []
  userTableData.value = []
  deviceTableData.value = []
  locTableData.value = []
  disposeCharts()
}

// 销毁所有图表
const disposeCharts = () => {
  if (projectChart) {
    projectChart.dispose()
    projectChart = null
  }
  if (userChart) {
    userChart.dispose()
    userChart = null
  }
  if (locChart) {
    locChart.dispose()
    locChart = null
  }
}

// 获取工时数据
const fetchWorkloadData = async () => {
  if (!selectedTimeRange.value || selectedTimeRange.value.length !== 2) return
  
  try {
    loading.value = true
    
    const [startDate, endDate] = selectedTimeRange.value

    // 获取所有项目工时数据（只需要时间段参数）
    const projectRes = await listAllProjectWorkloadStats({
      projectId: selectedProject.value,
      startDate,
      endDate
    })
    
    if (projectRes.success && projectRes.data.data) {
      projectTableData.value = projectRes.data.data
      initProjectChart(projectRes.data.data)
    } else {
      projectTableData.value = []
      initProjectChart([])
    }
    
    // 只有当选择了具体项目时，才查询人员和设备数据
    if (selectedProject.value) {
      // 获取人员工时数据
      const userRes = await listUserWorkloadStats({
        projectId: selectedProject.value,
        startDate,
        endDate
      })
      
      if (userRes.success && userRes.data.data) {
        userTableData.value = userRes.data.data
        initUserChart(userRes.data.data)
      } else {
        userTableData.value = []
        initUserChart([])
      }
      
      // 获取试验地点工时数据
      const locRes = await listLocWorkloadStats({
        projectId: selectedProject.value,
        startDate,
        endDate
      })
      
      if (locRes.success && locRes.data.data) {
        locTableData.value = locRes.data.data
        initLocChart(locRes.data.data)
      } else {
        locTableData.value = []
        initLocChart([])
      }
      
    } else {
      // 如果没有选择具体项目，清空人员和设备数据
      userTableData.value = []
      deviceTableData.value = []
      locTableData.value = []
      disposeCharts()
    }
  } catch (error) {
    console.error('获取工时数据失败:', error)
    projectTableData.value = []
    userTableData.value = []
    deviceTableData.value = []
    locTableData.value = []
    disposeCharts()
  } finally {
    loading.value = false
  }
}

// 初始化人员工时图表
const initUserChart = (data: any[]) => {
  if (!userChartContainer.value) return
  
  // 销毁旧图表
  if (userChart) {
    userChart.dispose()
  }
  
  userChart = echarts.init(userChartContainer.value)
  
  // 如果没有数据，显示空状态
  if (!data || data.length === 0) {
    const option = {
      title: {
        text: '试验人员工时统计',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      graphic: {
        type: 'text',
        left: 'center',
        top: 'middle',
        style: {
          text: '暂无数据',
          fontSize: 16,
          fill: '#999'
        }
      }
    }
    userChart.setOption(option)
    return
  }
  
  const option = {
    title: {
      text: '试验人员工时统计',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['试验时数', '试验准备时数', '加班时数'],
      top: 30
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.userName),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '小时数(h)'
    },
    series: [
      {
        name: '试验时数',
        type: 'bar',
        data: data.map(item => item.testHour),
        itemStyle: {
          color: '#5470C6'
        }
      },
      {
        name: '试验准备时数',
        type: 'bar',
        data: data.map(item => item.prepHour),
        itemStyle: {
          color: '#91CC75'
        }
      },
      {
        name: '加班时数',
        type: 'bar',
        data: data.map(item => item.overtimeHour),
        itemStyle: {
          color: '#EE6666'
        }
      }
    ]
  }
  
  userChart.setOption(option)
}
// 初始化项目工时图表
const initProjectChart = (data: any[]) => {
  if (!projectChartContainer.value) return
  
  // 销毁旧图表
  if (projectChart) {
    projectChart.dispose()
  }
  
  projectChart = echarts.init(projectChartContainer.value)
  
  // 如果没有数据，显示空状态
  if (!data || data.length === 0) {
    const option = {
      title: {
        text: '所有项目工时统计',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      graphic: {
        type: 'text',
        left: 'center',
        top: 'middle',
        style: {
          text: '暂无数据',
          fontSize: 16,
          fill: '#999'
        }
      }
    }
    projectChart.setOption(option)
    return
  }
  
  const option = {
    title: {
      text: '所有项目工时统计',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['试验时数', '试验准备时数', '加班时数', '总工时'],
      top: 30
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.projectName),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '小时数(h)'
    },
    series: [
      {
        name: '试验时数',
        type: 'bar',
        data: data.map(item => item.testHour),
        itemStyle: {
          color: '#5470C6'
        }
      },
      {
        name: '试验准备时数',
        type: 'bar',
        data: data.map(item => item.prepHour),
        itemStyle: {
          color: '#91CC75'
        }
      },
      {
        name: '加班时数',
        type: 'bar',
        data: data.map(item => item.overtimeHour),
        itemStyle: {
          color: '#EE6666'
        }
      },
      {
        name: '总工时',
        type: 'line',
        data: data.map(item => item.totalHour),
        itemStyle: {
          color: '#7238C1'
        },
        symbol: 'diamond',
        symbolSize: 8,
        lineStyle: {
          type: 'dashed'
        }
      }
    ]
  }
  
  projectChart.setOption(option)
}

// 初始化试验地点工时图表
const initLocChart = (data: any[]) => {
  if (!locChartContainer.value) return
  
  // 销毁旧图表
  if (locChart) {
    locChart.dispose()
  }
  
  locChart = echarts.init(locChartContainer.value)
  
  // 如果没有数据，显示空状态
  if (!data || data.length === 0) {
    const option = {
      title: {
        text: '试验地点工时统计',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      graphic: {
        type: 'text',
        left: 'center',
        top: 'middle',
        style: {
          text: '暂无数据',
          fontSize: 16,
          fill: '#999'
        }
      }
    }
    locChart.setOption(option)
    return
  }
  
  const option = {
    title: {
      text: '试验地点工时统计',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['试验时数', '试验准备时数', '天数'],
      top: 30
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.locName),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '小时数(h)',
        position: 'left'
      },
      {
        type: 'value',
        name: '天数',
        position: 'right'
      }
    ],
    series: [
      {
        name: '试验时数',
        type: 'bar',
        data: data.map(item => item.testHour),
        itemStyle: {
          color: '#5470C6'
        }
      },
      {
        name: '试验准备时数',
        type: 'bar',
        data: data.map(item => item.prepHour),
        itemStyle: {
          color: '#91CC75'
        }
      },
      {
        name: '天数',
        type: 'line',
        yAxisIndex: 1,
        data: data.map(item => item.workDays),
        itemStyle: {
          color: '#FAC858'
        },
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          type: 'solid',
          width: 2
        }
      }
    ]
  }
  
  locChart.setOption(option)
}

// 响应式调整图表大小
const resizeCharts = () => {
  projectChart?.resize()
  userChart?.resize()
  locChart?.resize()
}

onMounted(() => {
  fetchProjects()
  window.addEventListener('resize', resizeCharts)
})
</script>

<style scoped>
.chart-page {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  min-height: calc(100vh - 40px);
  overflow-y: auto;
  height: 100vh;
}

.filter-container {
  margin-bottom: 20px;
  position: sticky;
  top: 0;
  background: white;
  z-index: 10;
  padding: 10px 0;
  border-bottom: 1px solid #e8e8e8;
}

.filter-container h2 {
  margin: 0 0 16px 0;
  color: #1f2d3d;
  font-size: 20px;
}

.selectors {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.selector-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.selector-item span {
  font-weight: 500;
  color: #606266;
  white-space: nowrap;
}

.main-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-top: 20px;
  width: 100%;
  padding-bottom: 40px;
}

/* 统计区域 */
.stats-section {
  background: #fafafa;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
  overflow: hidden;
}

.stats-content {
  display: flex;
  gap: 20px;
  padding: 16px;
}

/* 图表容器 */
.chart-box {
  height: 400px;
  min-height: 400px;
  background: #fafafa;
  border-radius: 4px;
  padding: 16px;
  border: 1px solid #e8e8e8;
}

/* 表格容器 */
.table-box {
  display: flex;
  flex-direction: column;
  background: #fafafa;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
  overflow: hidden;
}

.table-header {
  padding: 12px 16px;
  font-weight: 500;
  background: #f5f5f5;
  border-bottom: 1px solid #e8e8e8;
  position: sticky;
  top: 0;
  z-index: 1;
}

.table-scroll {
  max-height: 400px;
  overflow: auto;
}

.chart-item {
  height: 350px;
  width: 100%;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
  color: #999;
  background: #fafafa;
  border-radius: 4px;
  border: 1px dashed #e8e8e8;
}

.empty-content {
  text-align: center;
}

.empty-content .arco-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #c0c4cc;
}

.empty-content p {
  margin: 0;
  font-size: 14px;
}

.stats-content .chart-box {
  flex: 2;
}

.stats-content .table-box {
  flex: 1;
}
.project-stats-section {
  margin-bottom: 20px;
  background: #fafafa;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
  overflow: hidden;
}

.section-title {
  padding: 12px 16px;
  font-weight: 500;
  background: #f5f5f5;
  border-bottom: 1px solid #e8e8e8;
  font-size: 16px;
  color: #1f2d3d;
}

.project-charts {
  display: flex;
  gap: 20px;
  padding: 16px;
}

.project-chart-box {
  flex: 2;
  height: 400px;
  background: white;
  border-radius: 4px;
  padding: 16px;
  border: 1px solid #e8e8e8;
}

.project-table-box {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
  overflow: hidden;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .stats-content {
    flex-direction: column;
  }
  
  .stats-content .chart-box,
  .stats-content .table-box {
    width: 100%;
  }
  
  .selectors {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .selector-item {
    width: 100%;
    justify-content: space-between;
  }
  
  .project-charts {
    flex-direction: column;
  }
  
  .project-chart-box,
  .project-table-box {
    width: 100%;
  }
}
</style>